import rich
import yaml
from pathlib import Path
from abc import ABC, abstractmethod
import os


class X_Config:
    def __init__(self):
        self.check = True
        self.set_config()
        if not self.check:
            rich.print("[yellow]Warning[/yellow] 初始化配置文件, 请重新运行")
            exit(0)

    def load_yaml(self, yaml_file: Path, default_config: dict = None):

        rich.print("[info] 加载配置文件: " + yaml_file.__str__())
        if not yaml_file.is_file():
            if default_config is not None:
                yaml_file.parent.mkdir(parents=True, exist_ok=True)
                with open(yaml_file, "w") as f:
                    yaml.safe_dump(default_config, f, sort_keys=False)
                rich.print(f"[yellow]Warning[/yellow]: 没有找到配置文件: {yaml_file}, 生成默认配置文件")
                self.check = False
                return default_config
            else:
                rich.print(f"[red]ERROR[/red] 加载配置文件: {yaml_file} 失败")
                self.check = False
                raise ValueError(f"加载配置文件: {yaml_file} 失败")

        with open(yaml_file, "r") as f:
            return yaml.safe_load(f)

    @abstractmethod
    def set_config(self):
        pass

    @abstractmethod
    def reset_config(self):
        pass
